// 配置axios默认设置
axios.defaults.baseURL = '/Parks';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

new Vue({
    el: '#app',
    data: {
        userInfo: {
            userName: '',
            roleId: ''
        },
        stats: {
            totalSeats: 0,
            availableSeats: 0,
            totalMembers: 0,
            todayIncome: 0
        },
        // 车位数据
        parkingSpots: [],
        highlightedSpots: [], // 存储被标记的车位ID
        // 搜索相关
        searchKey: '',
        // 最近记录
        // recentRecords: []
    },
    created() {
        this.checkLoginStatus();
        this.loadUserInfo();
        this.loadDashboardStats();
        this.loadParkingSpots();
        // this.loadRecentRecords();
    },
    methods: {
        checkLoginStatus() {
            axios.get('/checkLogin')
                .then(response => {
                    if (!response.data.success) {
                        window.location.href = 'login.html';
                    }
                })
                .catch(() => {
                    window.location.href = 'login.html';
                });
        },
        loadUserInfo() {
            axios.get('/userInfo')
                .then(response => {
                    if (response.data.success) {
                        this.userInfo = response.data.data;
                    }
                })
                .catch(error => {
                    console.error('Error loading user info:', error);
                });
        },
        loadDashboardStats() {
            axios.get('/dashboardStats')
                .then(response => {
                    if (response.data.success) {
                        const data = response.data.data;
                        // 使用动画效果显示数据
                        Object.keys(data).forEach(key => {
                            this.animateNumber(key, data[key]);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading dashboard stats:', error);
                });
        },
        // 加载车位状态
        loadParkingSpots() {
            axios.get('/parkingSeat/getAll')
                .then(response => {
                    if (response.data.code === 0) {
                        this.parkingSpots = response.data.data;
                        console.log(this.parkingSpots);
                    }
                })
                .catch(error => {
                    console.error('Error loading parking spots:', error);
                });
        },

        // // 加载最近记录
        // loadRecentRecords() {
        //     axios.get('/recentRecords')
        //         .then(response => {
        //             if (response.data.success) {
        //                 this.recentRecords = response.data.data;
        //             }
        //         })
        //         .catch(error => {
        //             console.error('Error loading recent records:', error);
        //         });
        // },
        // 处理搜索
        handleSearch() {
            // 清空之前的高亮
            this.highlightedSpots = [];
    
            // 如果搜索框为空，直接返回
            if (!this.searchKey.trim()) {
                return;
            }
    
            // 查找匹配的车位
            const matchedSpots = this.parkingSpots.filter(spot => 
                spot.carNumber && spot.carNumber.includes(this.searchKey.trim())
            );
        // 检查是否找到匹配的车位
        if (matchedSpots.length === 0) {
            alert('未找到该车牌，请确认输入是否正确。'); // 弹出提示
            return;
        }
            // 将匹配的车位ID添加到高亮数组中
            this.highlightedSpots = matchedSpots.map(spot => spot.seatId);
        },
        // 数字动画
        animateNumber(key, target) {
            const duration = 1000; // 动画持续时间（毫秒）
            const start = this.stats[key]; // 起始值
            const range = target - start; // 变化范围
            const startTime = performance.now(); // 开始时间

            const animate = (currentTime) => {
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);

                const easeOutQuad = 1 - Math.pow(1 - progress, 2);
                this.stats[key] = Math.round(start + (range * easeOutQuad));

                if (progress < 1) {
                    requestAnimationFrame(animate);
                }
            };

            requestAnimationFrame(animate);
        },
        handleLogout() {
            axios.post('/logout')
                .then(() => {
                    window.location.href = 'login.html';
                })
                .catch(error => {
                    console.error('Error during logout:', error);
                });
        },
        getStatusClass(status, isHighlighted) {
            const statusMap = {
                0: 'available',  // 空闲
                1: 'occupied',   // 占用
                2: 'maintenance'  // 维护中
            };
            const baseClass = statusMap[status] || '';
            return isHighlighted ? `${baseClass} highlighted` : baseClass; // 添加高亮类
        }
        // showSpotInfo(spot) {
        //     spot.isHovered = true; // 鼠标悬停时显示信息
        // },
        // hideSpotInfo(spot) {
        //     spot.isHovered = false; // 鼠标离开时隐藏信息
        // }
    }
}); 